<?php
/**
 * $Id: index.php 245 2006-02-14 07:43:25Z sam $
 *
 * FGS is the legal property of its developers, whose names are too numerous
 * to list here.  Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

class fgsBase {

	var $pages = array();
	var $default_page = false;

	function fgsBase() {
	}

	function getBaseUrl() {
		$dir = dirname($_SERVER['SCRIPT_NAME']);
		if ($dir[strlen($dir)-1] != '/')
			$dir .= '/';
		return $dir;
	}

	function getParams() {
		return explode('/', $_GET['p']);
	}

	function getParam($key = 0) {
		$p = explode('/', $_GET['p']);
		return $p[$key];
	}

	function shiftParam() {
		$p = explode('/', $_GET['p']);
		$ret = array_shift($p);
		$_GET['p'] = implode('/', $p);
		return $ret;
	}

	function isParam($key) {
		if (!empty($_GET['p'])) {
			$p = explode('/', $_GET['p']);
			return isset($p[$key]);
		}
		return false;
	}

	function link($name, $params = false) {
		$link_type = fgs::config('url_type');
		
		$p = array();
		$p[] = $name;
		if (is_array($params) && count($params))
			foreach ($params as $value) 
				$p[] = $value;
				
		$link = implode('/', $p);
		switch ($link_type) {
			case 'clean':
				$link = fgsBase::getBaseUrl() . $link;
				break;
			default:
				$link = fgsBase::getBaseUrl() . '?p=' . $link;
				break;
		}
		
		return $link;
	}

	function linkPage($title, $name, $params = false) {
		$link = fgsBase::link($name, $params);
		return sprintf('<a href="%s">%s</a>', $link, $title);
	}

	function image($img, $ext = 'png') {
		return sprintf('<img src="%sstyles/%s.%s"/>', fgsBase::getBaseUrl(), $img, $ext);
	}

	function redirect($name, $params = false) {
		$link = fgsBase::link($name, $params);
		header(sprintf('Location: %s', $link));
		exit;
	}

	function addPage($name, $permissions = 0) {
		$this->pages[$name] = array(
			'perm' => $permissions
		);
		if ($this->default_page === false)
			$this->default_page = $name;
	}

	function setPageParam($name, $key, $value) {
		$this->pages[$name][$key] = $value;
	}

	function getPageParam($name, $key) {
		return $this->pages[$name][$key];
	}

	function getTemplateIncludeFilename($page) {
		return sprintf('scripts/pages/includes/%s.php', $page);
	}

	function getTemplateFilename($page) {
		return sprintf('scripts/pages/templates/%s.php', $page);
	}

	function createCache($page, $filename) {

		// open file
		$fp = @fopen($filename, 'wb');
		if (!$fp)
			return false;

		// start capture of rendering
		ob_start();
		
		// include template
		$tpl = $this->getTemplateFilename($page);
		if (file_exists($tpl))
			include($tpl);

		// get data
		$data = ob_get_contents();
		ob_end_clean();

		// write to file
		if (!fwrite($fp, $data))	
			return false;
		fclose($fp);

		return true;
		
	}

	function showCache($page) {
		
		// get lifetime
		$lifetime = (int)$this->getPageParam($page, 'cache_lifetime');
		if ($lifetime == 0)
			$lifetime = 3600;

		// get cache path
		$cache_path = fgs::config('cache_path');
		if (empty($cache_path))
			return false;

		// calculate pagename
		$pagename = $page;
		$pagename .= fgs::config('page');
		$pagename .= $this->getPageParam($page, 'cache_salt');
		$params = $this->getParams();
		foreach ($params as $param)
			$pagename .= $param;
		$pagename = md5($pagename);

		// construct filename
		$filename = sprintf('%s/%s', $cache_path, $pagename);

		// create cache if not exist
		if (!file_exists($filename)) {
				if (!$this->createCache($page, $filename))
					return false;
		// check if lifetime is out
		} else if (time() - filemtime($filename) > $lifetime) {
				if (!$this->createCache($page, $filename))
					return false;
		}

		// show cache
		echo file_get_contents($filename);
		return true;
	}

	function prepend($page) {
		// include preprocess template
		$inc = $this->getTemplateIncludeFilename($page);
		if (file_exists($inc))
			include($inc);
	}

	function show($page, $prepend = true) {
		if ($this->getPageParam($page, 'cache'))
			if ($this->showCache($page))
				return true;

		// include preprocess template
		if ($prepend) {
			$inc = $this->getTemplateIncludeFilename($page);
			if (file_exists($inc))
				include($inc);
		}

		// include template
		$tpl = $this->getTemplateFilename($page);
		if (file_exists($tpl))
			include($tpl);

		return true;
	}

	function fix_magic_quotes_gpc(& $vals) {
		if (!get_magic_quotes_gpc())
			return;
		if (is_array($vals)) {
			foreach ($vals as $k => $v) {
				fgsBase::fix_magic_quotes_gpc($v);
				$vals[$k] = $v;
			}
		} else {
			$vals = stripslashes($vals);
		}
		return;
	}

	function clearAuth() {
		$_SESSION['is_admin'] = false;
		$_SESSION['old_login'] = time();
		header('HTTP/1.0 401 Unauthorized');
		fgsBase::redirect('main');
		exit;
	}

	function run() {
		$page = fgsBase::shiftParam();
		if (!in_array($page, array_keys($this->pages)))
			$_SESSION['page'] = $page = $this->default_page;
		if ($page != '' && $_SESSION['page'] != $page)
			$_SESSION['page'] = $page;
		else if ($_SESSION['page'] == '')
			$_SESSION['page'] = $page = $this->default_page;
		else
			$page = $_SESSION['page'];

		fgs::config('page', $page);
		$_SESSION['page'] = $page;

		$this->fix_magic_quotes_gpc($_POST);
		$this->fix_magic_quotes_gpc($_GET);

		if ($this->getPageParam($page, 'auth')) {
			$_SESSION['is_admin'] = false;
			$login = $_SERVER['PHP_AUTH_USER'];
			$pass = $_SERVER['PHP_AUTH_PW'];
			if ($_SESSION['old_login'] != $login) {
				if ($_SESSION['old_login'] == '') {
					$_SESSION['old_login'] = $login;
				} else {
					$_SESSION['old_login'] = $login;
					$login = '';
				}
			}
			$check = true;


			if ($login == 'admin' && $pass == fgs::config('admin_pass'))
				$check = false;

			if ($check && !empty($login)) {
				if (fgsUsers::checkLogin($login, md5($pass))) {
					$user = fgsUsers::get($login);
					if ($user['is_admin'])
						$check = false;
				}
			} 

			if ($check) {
				header('WWW-Authenticate: Basic realm="FGS Administration"');
				header('WWW-Authenticate: NTLM', false);
				header('HTTP/1.0 401 Unauthorized');
				echo tr('Freegs: Access denied');
				exit;
			} else {
				$_SESSION['is_admin'] = true;
			}
		}

		header('Content-Type: text/html; charset=utf-8');

		ob_start();
		$this->show($page);
		$data = ob_get_contents();
		ob_end_clean();
		
		$this->show('header');
		echo $data;
		$this->show('footer');

	}

}

?>
